package gitpack

import (
	"fmt"
	"io"

	"gitee.com/thubcc/p2pgit/format"
	"gitee.com/thubcc/p2pgit/types"
	"github.com/a4a881d4/gitcrawling/packext"
)

// TravelGitPackFile travel git pack file
func TravelGitPackFile(idxf string, cb func(h *format.Header, b []byte) error) error {

	idx, err := packext.NewIdxObj(idxf)
	if err != nil {
		return err
	}
	defer idx.Close()
	// p := utils.NewProgress(path.Base(idxf)+":", 100000)
	// p.Verbosity ^= utils.Precent | utils.Total
	// p.Init()
	// defer p.End()
	for {
		err = idx.Next(func(o *packext.ObjEntry, h, b []byte) error {
			// p.Done()
			r := &format.Header{}
			r.Header32 = *types.NewHeader32FromOE(o)
			err := r.HeaderFromByte(h)
			if err != nil {
				fmt.Println(err)
				return err
			}
			return cb(r, b)
		})
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}
	}
	return nil
}
